<?php
class Contest_model extends MY_Model {
	private $module = 'contest';
	private $table = 'contest';

	function getsearchContent($limit,$page){
		$this->db->select('*');
		$this->db->limit($limit,$page);
		$this->db->order_by($this->input->post('func_order_by'),$this->input->post('order_by'));
		if($this->input->post('content')!='' && $this->input->post('content')!='type here...'){
			$this->db->where('(`title` LIKE "%'.$this->input->post('content').'%" OR `content` LIKE "%'.$this->input->post('content').'%" OR `type` = "'.$this->input->post('content').'")');
		}
		if($this->input->post('dateFrom')!='' && $this->input->post('dateTo')==''){
			$this->db->where('created >= "'.date('Y-m-d 00:00:00',strtotime($this->input->post('dateFrom'))).'"');
		}
		if($this->input->post('dateFrom')=='' && $this->input->post('dateTo')!=''){
			$this->db->where('created <= "'.date('Y-m-d 23:59:59',strtotime($this->input->post('dateTo'))).'"');
		}
		if($this->input->post('dateFrom')!='' && $this->input->post('dateTo')!=''){
			$this->db->where('created >= "'.date('Y-m-d 00:00:00',strtotime($this->input->post('dateFrom'))).'"');
			$this->db->where('created <= "'.date('Y-m-d 23:59:59',strtotime($this->input->post('dateTo'))).'"');
		}
		$query = $this->db->get(PREFIX.$this->table);

		if($query->result()){
			return $query->result();
		}else{
			return false;
		}
	}
	
	function getTotalsearchContent(){
		$this->db->select('*');
		if($this->input->post('content')!='' && $this->input->post('content')!='type here...'){
			$this->db->where('(`title` LIKE "%'.$this->input->post('content').'%" OR `content` LIKE "%'.$this->input->post('content').'%" OR `type` = "'.$this->input->post('content').'")');
		}
		if($this->input->post('dateFrom')!='' && $this->input->post('dateTo')==''){
			$this->db->where('created >= "'.date('Y-m-d 00:00:00',strtotime($this->input->post('dateFrom'))).'"');
		}
		if($this->input->post('dateFrom')=='' && $this->input->post('dateTo')!=''){
			$this->db->where('created <= "'.date('Y-m-d 23:59:59',strtotime($this->input->post('dateTo'))).'"');
		}
		if($this->input->post('dateFrom')!='' && $this->input->post('dateTo')!=''){
			$this->db->where('created >= "'.date('Y-m-d 00:00:00',strtotime($this->input->post('dateFrom'))).'"');
			$this->db->where('created <= "'.date('Y-m-d 23:59:59',strtotime($this->input->post('dateTo'))).'"');
		}
		$query = $this->db->count_all_results(PREFIX.$this->table);

		if($query > 0){
			return $query;
		}else{
			return false;
		}
	}
	
	function getDetailManagement($id){
		$this->db->select('*');
		$this->db->where('id',$id);
		$query = $this->db->get(PREFIX.$this->table);

		if($query->result()){
			return $query->result();
		}else{
			return false;
		}
	}
	
	function saveManagement($fileName=''){
		if($this->input->post('statusAdmincp')=='on'){
			$status = 1;
		}else{
			$status = 0;
		}

		if($this->input->post('hiddenIdAdmincp')==0){
			//Kiểm tra đã tồn tại chưa?
			$checkData = $this->checkData($this->input->post('titleAdmincp'));
			if($checkData){
				print 'error-title-exists';
				exit;
			}
			
			$checkSlug = $this->checkSlug($this->input->post('slugAdmincp'));
			if($checkSlug){
				print 'error-slug-exists';
				exit;
			}
			$data = array(
				'title'=> $this->input->post('titleAdmincp'),
				'slug'=> $this->input->post('slugAdmincp'),
				'description'=> $this->input->post('descAdmincp'),
				'content'=> $this->input->post('contentAdmincp'),
				'image'=> $fileName['image'],
				'status'=> $status,
				'created'=> date('Y-m-d H:i:s',time()),
			);
			if($this->db->insert(PREFIX.$this->table,$data)){
				modules::run('admincp/saveLog',$this->module,$this->db->insert_id(),'Add new','Add new');
				return true;
			}
		}else{
			$result = $this->getDetailManagement($this->input->post('hiddenIdAdmincp'));
			//Kiểm tra đã tồn tại chưa?
			if($result[0]->title!=$this->input->post('titleAdmincp')){
				$checkData = $this->checkData($this->input->post('titleAdmincp'));
				if($checkData){
					print 'error-title-exists';
					exit;
				}
			}
			
			if($result[0]->slug!=$this->input->post('slugAdmincp')){
				$checkSlug = $this->checkSlug($this->input->post('slugAdmincp'));
				if($checkSlug){
					print 'error-slug-exists';
					exit;
				}
			}
			
			//Xử lý xóa hình khi update thay đổi hình
			if($fileName['image']==''){
				$fileName['image'] = $result[0]->image;
			}else{
				@unlink(BASEFOLDER.DIR_UPLOAD_NEWS.$result[0]->image);
			}
			//End xử lý xóa hình khi update thay đổi hình
			
			$data = array(
				'title'=> $this->input->post('titleAdmincp'),
				'slug'=> $this->input->post('slugAdmincp'),
				'description'=> $this->input->post('descAdmincp'),
				'content'=> $this->input->post('contentAdmincp'),
				'image'=> $fileName['image'],
				'status'=> $status
			);
			modules::run('admincp/saveLog',$this->module,$this->input->post('hiddenIdAdmincp'),'','Update',$result,$data);
			$this->db->where('id',$this->input->post('hiddenIdAdmincp'));
			if($this->db->update(PREFIX.$this->table,$data)){
				return true;
			}
		}
		return false;
	}
	
	function checkData($title){
		$this->db->select('id');
		$this->db->where('title',$title);
		$this->db->limit(1);
		$query = $this->db->get(PREFIX.$this->table);

		if($query->result()){
			return true;
		}else{
			return false;
		}
	}
	
	function checkSlug($slug){
		$this->db->select('id');
		$this->db->where('slug',$slug);
		$this->db->limit(1);
		$query = $this->db->get(PREFIX.$this->table);

		if($query->result()){
			return true;
		}else{
			return false;
		}
	}
	
	/*----------------------FRONTEND----------------------*/
	function contest_register($data)
	{
		if($this->db->insert(TBL_CONTEST,$data))
		{
			return true;
		}
		return false;
	}
	
	function contest_user($data)
	{
		if($this->db->insert(TBL_USERS,$data))
		{
			return true;
		}
		return false;
	}
	
	function contest_detail($id)
	{
		$this->db->select('*');
		$this->db->where('status',1);
		$this->db->where('id',$id);
		$query = $this->db->get(PREFIX.$table);
		if($query->num_rows() == 1)
		{
			return $query->result();
		}
		return false;
	}
	
	function get_next($contest_id)
	{
		$this->db->select('id');
		$this->db->where('status',1);
		$this->db->where('id > ',$contest_id);
		$this->db->order_by('id','ASC');
		$this->db->limit(1);
		$query = $this->db->get(TBL_CONTEST);
		if($query->num_rows() == 1)
		{
			return $query->row();
		}
		return false;
	}
	
	function get_prev($contest_id)
	{
		$this->db->select('id');
		$this->db->where('status',1);
		$this->db->where('id < ',$contest_id);
		$this->db->order_by('id','DESC');
		$this->db->limit(1);
		$query = $this->db->get(TBL_CONTEST);
		if($query->num_rows() == 1)
		{
			return $query->row();
		}
		return false;
	}
	
	function contest_check_like($ss_user_id,$id)
	{
		$this->db->select('id');
		$this->db->where('contest_id',$id);
		$this->db->where('user_id',$ss_user_id);
		$this->db->where('status',1);
		$query = $this->db->get(TBL_LIKE);
		if($query->num_rows() >= 1)
		{
			return false;
		}
		return true;
	}
	
	function contest_check_ip($ip,$id)
	{
		$this->db->select('id');
		$this->db->where('ip',$ip);
		$this->db->where('contest_id',$id);
		$this->db->where('status',1);
		$query = $this->db->get(TBL_LIKE);
		if($query->num_rows() >= 5)
		{
			return false;
		}
		return true;
	}

	function contest_check_ban($ip)
	{
		$this->db->select('id');
		$this->db->where('status',1);
		$this->db->where('ip',$ip);
		$query = $this->db->get(TBL_BAN);
		if($query->num_rows() >= 0)
		{
			return false;
		}
		return true;
	}
	
	// Validate
	
	function check_fullname($fullname){
        $data = array();
        if (empty($fullname)) {
            $data = array(
                'status' => 0,
                'code' => 'fullname-error',
                'message' => 'Vui lòng nhập tên của bạn.'
            );
            return $data;
        }

        if (preg_match('/[0-9\'\/~`\!@#\$%\^&\*\(\)_\-\+=\{\}\[\]\|;:"\<\>,\?\\\]/', $fullname)) {
            $data = array(
                'status' => 0,
                'code' => 'fullname-error',
                'message' => 'Vui lòng nhập tên của bạn.'
            );
            return $data;
        }
        return false;
    }
	
	function check_address($address) {
        $data = array();

        if (empty($address)) {
            $data = array(
                'status' => 0,
                'code' => 'address-error',
                'message' => 'Vui lòng nhập địa chỉ của bạn.'
            );
            return $data;
        }

        return false;
    }
	
	function check_phone($phone) {
        $data = array();
        if (empty($phone)) {
            $data = array(
                'status' => 0,
                'code' => 'phone-error',
                'message' => 'Vui lòng nhập điện thoại của bạn.'
            );
            return $data;
        }

        if (!validate_length($phone, 10, 11) || !is_numeric($phone)) {
            $data = array(
                'status' => 0,
                'code' => 'phone-error',
                'message' => 'Số điện thoại không hợp lệ. Vui lòng nhập lại.'
            );
            return $data;
        }

        return false;
    }
	
	function check_email($email, $update = false) {
        $data = array();

        if (empty($email)) {
            $data = array(
                'status' => 0,
                'code' => 'email-error',
                'message' => 'Vui lòng nhập email của bạn.'
            );
            return $data;
        }

        if (!validate_email($email)) {
            $data = array(
                'status' => 0,
                'code' => 'email-error',
                'message' => 'Email không hợp lệ. Vui lòng nhập lại.'
            );
            return $data;
        }

        if ($update == false) {
            if (!$this->is_unique($email, 'email',TBL_USERS)) {
                $data = array(
                    'status' => 0,
                    'code' => 'email-error',
                    'message' => 'Email đã được đăng ký. Vui lòng nhập email khác.'
                );
                return $data;
            }
        }

        return false;
    }
	
	function is_unique($data, $field, $table) {
        $this->db->where($field, $data);
		$this->db->limit(1);      
        $query = $this->db->get($table);
        if ($query->num_rows() > 0) {
            return false;
        } else {
            return true;
        }
    }
	// End validate
	
	function contest_winner()
	{
		$this->db->select('*');
		$this->db->where('status',1);
		$this->db->where('is_winner',1);
		$query = $this->db->get(TBL_CONTEST);
		if($query->num_rows() > 0)
		{
			return $query->result();
		}
		return false;
	}
	
	/*--------------------END FRONTEND--------------------*/
}